package com.songcha.sakura.service

import android.app.NotificationManager
import android.app.Service
import android.content.Intent
import android.os.*
import androidx.core.app.NotificationCompat
import com.songcha.library_common.util.LogUtil
import com.songcha.library_common.util.ToastUtil
import com.songcha.sakura.MyApplication
import com.songcha.sakura.R
import com.songcha.sakura.config.DownloadConfig
import com.songcha.sakura.download.*
import com.songcha.sakura.download.base.DownloadDelegate
import com.songcha.sakura.download.m3u8.M3u8DownloadOption
import com.songcha.sakura.download.m3u8.M3u8Downloader
import com.songcha.sakura.download.m3u8.M3u8TsConverter
import com.songcha.sakura.download.m3u8.M3u8UrlConverter
import com.songcha.sakura.ui.activity.MainActivity
import com.songcha.sakura.util.FileUtil
import com.songcha.library_common.util.NotificationUtil
import com.songcha.sakura.download.base.DownloadTask
import java.io.File


class DownloadService:Service(),IDownloaderListener  {

    companion object{
        val NOTIFICATION_ID=100

        val MSG_START_DOWNLOAD=1
        val MSG_DOWNLOAD_RET=2
        //val MSG_GET_INSTANCE=3
        val MSG_DOWNLOAD_INITIALIZE=4
        val MSG_DOWNLOAD_START=5
        val MSG_DOWNLOAD_UPDATE=6
        val MSG_DOWNLOAD_PAUSE=7
        val MSG_DOWNLOAD_COMPLETED=8
        val MSG_DOWNLOAD_ERROR=9
        val MSG_CONNECT_INITIALIZE=10
        val MSG_PAUSE_TASK=11
        val MSG_RESUME_TASK=12
        val MSG_CANCEL_TASK=13
        val MSG_GET_LOCAL_TASK_LIST=14
        val MSG_RET_LOCAL_TASK_LIST=15
        val MSG_CONNECT_INITIALIZE_RET=16
        val MSG_GET_TASK_LIST=17
        val MSG_RET_TASK_LIST=18
    }

    private var mClientMessenger:Messenger?=null
    private var mNotificationManager:NotificationManager?=null

    override fun onBind(intent: Intent?): IBinder? {
        //return MyBinder()
        LogUtil.log("download service bind")

       /* val notification=NotificationUtil.createForegroundNotification(
            this, R.mipmap.logo,"sakura","正在下载",100,
            "download channel id","download channel","this is a download channel"
        )
        NotificationUtil.notifyNotification(this,100,notification)*/
        //startForeground()
        return mServiceMessenger.binder
    }

    override fun onDestroy() {
        super.onDestroy()
        LogUtil.log("download service destroy")
    }

    override fun onUnbind(intent: Intent?): Boolean {
        return super.onUnbind(intent)
        LogUtil.log("download service unbind")
    }



    /*inner class MyBinder : Binder() {
       *//* fun startDownload(url:String,thumb:String,name:String){
            val ret=this@DownloadService.startDownload(url,thumb,name)

            //LogUtil.log("startDownload",url,filePath)

            if(ret>-1)
                ToastUtil.show("已添加到下载队列")
            //else
                //ToastUtil.show("下载失败$ret")

        }*//*

        fun getService():DownloadService{
            return this@DownloadService
        }
    }*/

    override fun onCreate() {
        super.onCreate()
        //Aria.download(this).register()
    }

    /*@Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    fun onGetLocalTask(event: LocalTaskEvent){
        EventBus.getDefault().removeStickyEvent(event)

    }
    */
    private fun showNotification(title:String,content:String,progress:Int){
        if(content.isEmpty()) return
        //LogUtil.log("showNotification",progress)
        val intent=Intent(this,MainActivity::class.java)
        intent.putExtra("enterByNotification",true)
        val notification= NotificationUtil.createForegroundNotification(
            this@DownloadService, R.mipmap.logo,title,content,
            "download channel id","download channel","this is a download channel",
            intent,true,true,false,progress, NotificationManager.IMPORTANCE_LOW,NotificationCompat.PRIORITY_LOW
        )
        if(mNotificationManager==null){
            mNotificationManager=NotificationUtil.getNotificationManager(this@DownloadService)
            NotificationUtil.startForeground(this@DownloadService,NOTIFICATION_ID,notification)
        }
        mNotificationManager!!.notify(NOTIFICATION_ID,notification)
    }

    private val mHandler=object: Handler(Looper.getMainLooper()){
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            //send to client

            when(msg.what){
                MSG_START_DOWNLOAD-> {
                    mClientMessenger=msg.replyTo
                    val bundle=msg.data
                    val url=bundle.getString("url")?:""
                    val thumb=bundle.getString("thumb")?:""
                    val fileName=bundle.getString("fileName")?:""
                    val ret=startDownload(url,thumb,fileName)

                    val msg=Message.obtain()
                    msg.what=MSG_DOWNLOAD_RET
                    msg.arg1=ret
                    mClientMessenger?.send(msg)

                }

                MSG_CONNECT_INITIALIZE->{
                    mClientMessenger=msg.replyTo
                    DownloadManager.setListener(this@DownloadService)

                    val msg=Message.obtain()
                    msg.what=MSG_CONNECT_INITIALIZE_RET
                    mClientMessenger?.send(msg)
                }

                MSG_PAUSE_TASK->{
                    val bundle=msg.data
                    bundle.classLoader=DownloadService::class.java.classLoader
                    val task=bundle.getParcelable<DownloadTask>("task")
                    if(task!=null)
                        DownloadManager.pauseTask(task)
                }
                MSG_RESUME_TASK->{
                    val bundle=msg.data
                    bundle.classLoader=DownloadService::class.java.classLoader
                    val task=bundle.getParcelable<DownloadTask>("task")
                    if(task!=null){
                        DownloadManager.resumeTask(task)
                    }

                }
                MSG_CANCEL_TASK->{
                    val bundle=msg.data
                    bundle.classLoader=DownloadService::class.java.classLoader
                    val url=bundle.getString("url")?:""
                    DownloadManager.cancelTask(url)
                }
                MSG_GET_LOCAL_TASK_LIST->{
                    DownloadManager.getLocalTask()
                    val msg=Message.obtain()
                    msg.what= MSG_RET_LOCAL_TASK_LIST
                    val bundle=Bundle()
                    bundle.putParcelableArray("task_list",DownloadManager.getTaskList().toTypedArray())
                    msg.data=bundle
                    mClientMessenger?.send(msg)

                }
                MSG_GET_TASK_LIST->{
                    val msg=Message.obtain()
                    msg.what=MSG_RET_TASK_LIST
                    val bundle=Bundle()
                    bundle.putParcelableArray("task_list",DownloadManager.getTaskList().toTypedArray())
                    msg.data=bundle
                    mClientMessenger?.send(msg)

                }

            }

        }
    }

    private var mServiceMessenger=Messenger(mHandler)


    fun startDownload(url: String, thumb: String, fileName: String): Int {
        if(url.isEmpty() || (!url.startsWith("http://") && !url.startsWith("https://"))){
            ToastUtil.show("无效的下载地址")
            return -1
        }
        //保存图片
        if(fileName.length<11) {
            ToastUtil.show("无效的文件名")
            return -6
        }

        var title=fileName.substring(11,fileName.length)
        val splitIndex = title.indexOf("-")
        if (splitIndex > -1) {
            title = title.substring(0, splitIndex)
        }

        //val comicPath = MyApplication.getContext().filesDir.absolutePath + "/" + title + "/"
        val comicPath = DownloadConfig.getVideoDownloadPath() + "/" + title + "/"
        if (!FileUtil.isDirExist(comicPath)) {
            FileUtil.mkDir(comicPath)
        }


        if(thumb.isNotEmpty()){
            val thumbPath = comicPath + "thumb.jpg"
            val thumbFile = File(thumbPath)
            if (!thumbFile.exists() || thumbFile.length() == 0L) {
                FileUtil.downloadImage(com.songcha.sakura.MyApplication.getContext(), thumb, thumbPath)
            }
        }


        //val uuid=(System.currentTimeMillis()/ 1000).toString()
       // val filePath = comicPath +uuid + "-" + titleEpoise +".m3u8"
        val filePath = comicPath +fileName +".m3u8"

        LogUtil.log("开始下载",url)

        val option = M3u8DownloadOption()
        option.filePath = filePath
        option.setPath()

        option.urlConverter = M3u8UrlConverter()
        option.tsConverter = M3u8TsConverter()

        return DownloadManager.create(this, url, option, DownloadDelegate(M3u8Downloader()))

    }


    override fun onInitialize(task: DownloadTask) {
        mClientMessenger?.let {
            val msg=Message.obtain()
            msg.what=MSG_DOWNLOAD_INITIALIZE
            val bundle=Bundle()
            bundle.putParcelable("task",task)
            msg.data=bundle
            it.send(msg)
        }

        //EventBus.getDefault().post(TaskEvent(TaskEventType.INITIALIZE,task))
    }

    override fun onStart(task: DownloadTask) {
        mClientMessenger?.let {
            val msg=Message.obtain()
            msg.what=MSG_DOWNLOAD_START
            val bundle=Bundle()
            bundle.putParcelable("task",task)
            msg.data=bundle
            it.send(msg)
        }
        val content=task.option.fileName.substring(10,task.option.fileName.length)
        showNotification("正在下载",content,task.progress)
        //EventBus.getDefault().post(TaskEvent(TaskEventType.START,task))
    }

    override fun onUpdate(task: DownloadTask) {
        mClientMessenger?.let {
            val msg=Message.obtain()
            msg.what = MSG_DOWNLOAD_UPDATE
            val bundle=Bundle()
            bundle.putParcelable("task",task)
            msg.data=bundle
            it.send(msg)
        }
        val content=task.option.fileName.substring(10,task.option.fileName.length)
        showNotification("正在下载",content,task.progress)
        //showNotification(task.option.fileName,task.progress)
        //EventBus.getDefault().post(TaskEvent(TaskEventType.UPDATE,task))
    }

    override fun onCompleted(task: DownloadTask) {
        mClientMessenger?.let {
            val msg=Message.obtain()
            msg.what = MSG_DOWNLOAD_COMPLETED
            val bundle=Bundle()
            bundle.putParcelable("task",task)
            msg.data=bundle
            it.send(msg)
        }
        val content=task.option.fileName.substring(10,task.option.fileName.length)
        showNotification("下载完成",content,0)

        //mNotificationManager?.cancel(NOTIFICATION_ID)
        //EventBus.getDefault().post(TaskEvent(TaskEventType.COMPLETED,task))
    }

    override fun onPause(task: DownloadTask) {
        mClientMessenger?.let {
            val msg=Message.obtain()
            msg.what = MSG_DOWNLOAD_PAUSE
            val bundle=Bundle()
            bundle.putParcelable("task",task)
            msg.data=bundle
            it.send(msg)
        }
        //EventBus.getDefault().post(TaskEvent(TaskEventType.PAUSE,task))
    }

    override fun onError(task: DownloadTask, e: Exception) {
        mClientMessenger?.let {
            val msg=Message.obtain()
            msg.what = MSG_DOWNLOAD_ERROR
            val bundle=Bundle()
            bundle.putParcelable("task",task)
            msg.data=bundle
            it.send(msg)
        }
        showNotification("下载失败",task.option.fileName,0)
        //EventBus.getDefault().post(TaskEvent(TaskEventType.ERROR,task))
    }

    override fun onCancel(task: DownloadTask) {
        mClientMessenger?.let {
            val msg=Message.obtain()
            msg.what = MSG_CANCEL_TASK
            val bundle=Bundle()
            bundle.putParcelable("task",task)
            msg.data=bundle
            it.send(msg)
        }
        mNotificationManager?.cancel(NOTIFICATION_ID)
        //EventBus.getDefault().post(TaskEvent(TaskEventType.ERROR,task))
    }

}